<template>
  <div class="app-container">
    <el-tabs v-model="queryParams.status" @tab-click="resetQuery">
      <el-tab-pane
        v-for="dict in dict.type.card_status"
        :key="dict.value"
        :label="dict.label"
        :name="dict.value"
      />
    </el-tabs>
    <el-form
      v-show="showSearch"
      v-if="queryParams.status !== '400'"
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
      label-width="68px"
    >

      <el-form-item label="时间范围" prop="time">
        <el-date-picker
          v-model="queryParams.time"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="卡号" prop="cardNumber">
        <el-input
          v-model="queryParams.cardNumber"
          placeholder="请输入卡号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="导出状态" prop="isExp">
        <el-select v-model="queryParams.isExp" clearable placeholder="可多选">
          <el-option v-for="(exp,expIdx) in dict.type.export_status" :key="expIdx" :value="exp.value" :label="exp.label" />
        </el-select>
      </el-form-item>
      <el-form-item label="卡类型" prop="cardType">
        <el-select v-model="queryParams.cardType" clearable placeholder="可多选">
          <el-option v-for="(dit,idx) in dict.type.card_type" :key="idx" :value="dit.value" :label="dit.label" />
        </el-select>
      </el-form-item>
      <el-form-item
        v-if="['200', '100'].includes(queryParams.status)"
        label="手机尾号"
        prop="phone"
      >
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入后四位"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <template v-if="['200', '1', '100'].includes(queryParams.status)">
        <el-col v-if="['200', '1'].includes(queryParams.status)" :span="1.5">
          <el-button
            v-hasPermi="['system:dyUserinfo:edit']"
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="multiple"
            @click="handleOver"
          >完成</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['system:dyUserinfo:remove']"
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
      </template>
      <el-col
        v-if="['200', '1', '100'].includes(queryParams.status)"
        :span="1.5"
      >
        <el-button
          v-hasPermi="['system:dyUserinfo:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar
        :show-search.sync="showSearch"
        @queryTable="() => getList()"
      />
    </el-row>

    <zm-table-data
        :data="tableParams.data"
        :columns="columns"
        :fetch="getList"
        :createFetch="false"
        :table-params="tableParams"
        :row-class-name="tableRowClassName"
        :show-page="true"
        :mutilple="true"
        @select="handleSelect"
        @selection-change="getSelectionIds"
        :checked="checkedArr"
      />

    <Detail v-if="showDetail" v-model="showDetail" :obj="currentItem" />
    <Release
      v-if="showReleaseDialog"
      v-model="showReleaseDialog"
      :obj="currentItem"
      :release-status="commandStatus"
      @after-save="getList"
    />
  </div>
</template>

<script>
import {
  listDyUserinfo,
  getDyUserinfo,
  delDyUserinfo,
  addDyUserinfo,
  updateDyUserinfo,
  delDyUserOver
} from '@/api/system/dyUserinfo'
import Detail from './components/DetailDialog.vue'
import { mapGetters } from 'vuex'
import { operateBtn,columns } from './const'
import tableMixin from '@/mixins/zmTableMixin'
import Release from './components/ReleaseDialog.vue'
var MobileDetect = require('mobile-detect/mobile-detect')
const speechSynth = window.speechSynthesis
const speech = new SpeechSynthesisUtterance()
console.log(MobileDetect)
export default {
  name: 'DyUserinfo',
  dicts: ['card_status', 'online_status', 'card_type', 'export_status'],
  components: { Detail, Release },
  mixins: [tableMixin],
  filters: {
    mobileType(userAgent) {
      var md = new MobileDetect(userAgent) // 初始化mobile-detect
      var os = md.os() // 获取系统
      var model = ''
      if (os == 'iOS') {
        // ios系统的处理
        const isIpad = md.mobile() === 'iPad'
        os = md.os() + md.version(isIpad ? 'iPad' : 'iPhone')
        model = md.mobile()
      } else if (os == 'AndroidOS') {
        // Android系统的处理
        os = md.os() + md.version('Android')
        var sss = userAgent.split(';')
        var i = sss.findIndex(item => item.includes('Build/'))
        if (i > -1) {
          model = sss[i].substring(0, sss[i].indexOf('Build/'))
        }
      } else {
        var Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod']
        model = Agents.indexOf(os) > -1 ? os : 'PC'
      }
      return os + ' ' + model
    }
  },
  data() {
    return {
      operateBtn,
      timer: null,
      showDetail: false,
      showReleaseDialog: false,
      commandStatus: 1,
      currentItem: {},
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      intervalList: [],
      intervalTotal: 0,
      // 信息表格数据
      dyUserinfoList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        phone: null,
        country: null,
        city: null,
        cardNumber: null,
        cvv: null,
        time: [],
        status: '1',
        refUrl: null,
        isExp: null,
        cardType: null,
        ids: [], // 如果需要按照选中的导出，添加这个数组参数。记录id非orderId
        params: {
          beginCreatTime: null,
          endCreatTime: null
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    }
  },
  created() {
    // this.startPolling()
  },
  computed: {
    columns(){
      return columns(this)
    },
    ...mapGetters(['appConfig']),
    highlightCards() {
      return this.appConfig.highlightCards.split(',')
    },
    refuseCards() {
      return this.appConfig.refuseCards.split(',')
    },
    refreshRate() {
      return this.appConfig.refreshRate
    }
  },
  beforeRouteLeave(to, from, next) {
    // ...
    this.stopPolling()
    next()
  },
  beforeDestroy() {
    this.stopPolling()
  },
  methods: {
    handleCommand(status, row) {
      const id = row.id || this.ids
      if ([2, 3, 5, 7, 9].includes(+status)) {
        this.currentItem = row
        this.commandStatus = +status
        this.showReleaseDialog = true
      } else {
        this.$modal
          .confirm('是否确认处理？')
          .then(function() {
            return updateDyUserinfo({ id, status })
          })
          .then(() => {
            this.getList()
            this.$modal.msgSuccess('放行成功!')
          })
          .catch(() => {})
      }
    },

    tableRowClassName({ row }) {
      // 根据行数据判断并返回类名
      if (row.isOnline === 1) {
        return 'on-line'
      }
      if (row.isRefuse === 1) {
        return 'refuse'
      }
      if (row.isHighlight === 1) {
        return 'high-light'
      }
      return ''
    },
    startPolling() {
      // 设定轮询间隔，例如每5秒轮询一次
      const interval = this.refreshRate * 1000
      this.timer = setInterval(() => {
        this.getList('1')
      }, interval)
      // if (+this.queryParams.status !== 1) {
      this.getList()
      // }
    },
    stopPolling() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    speak(text = '叮咚!您有新的订单需要处理!') {
      speech.text = text // 播报消息
      speech.lang = 'zh-CN' // 设置语言
      speech.pitch = 2
      speech.volume = 1
      speech.rate = 1
      speechSynth.speak(speech) // 播报消息
    },
    cancelSpeak() {
      speechSynth.cancel()
    },
    // 使用例子
    /** 查询信息列表 */
    getList(status, pageParams) {
      this.loading = false
      if (this.queryParams.time != null && this.queryParams.time != '') {
        this.queryParams.params.beginCreatTime = this.queryParams.time[0]
        this.queryParams.params.endCreatTime = this.queryParams.time[1]
      } else {
        this.queryParams.params.beginCreatTime = null
        this.queryParams.params.endCreatTime = null
      }

      let params = { ...this.queryParams }
      if (status) {
        params.status = status
      }
      params = { ...params, ...pageParams }
      if (status === '1') {
        params = { ...this.queryParams, status: '1', pageNum: 1 }
      }
      listDyUserinfo({ ...params }).then((response) => {
        const resList = response.rows.map((item) => {
          const cardType = item.cardType
            ? item.cardType.split(',')[0].toUpperCase()
            : ''
          const text =
            cardType === 'CREDIT'
              ? 'C'
              : cardType === 'DEBIT'
                ? 'D'
                : cardType === 'PREPAID'
                  ? 'P'
                  : ''
          const highTitle =
            item.cardNumber && item.cardNumber.length > 6
              ? `${item.cardNumber.substr(0, 6)}`
              : item.cardNumber
          return {
            ...item,
            cardNumberShow: `${item.cardNumber}-[${text}]`,
            isHighlight: this.highlightCards.includes(highTitle) ? 1 : 0,
            isRefuse: this.refuseCards.includes(highTitle) ? 1 : 0
          }
        })
        if (status === '1') {
          if (response.total > this.intervalTotal && this.intervalTotal !== 0) {
            this.cancelSpeak()
            this.speak()
          }
          if (
            this.queryParams.status === '1' &&
            this.queryParams.pageNum === 1
          ) {
            this.dyUserinfoList = resList
            this.total = response.total
            this.intervalTotal = response.total
          } else {
            this.intervalTotal = response.total
            this.intervalList = resList
          }
        } else {
          this.dyUserinfoList = resList
          this.total = response.total
        }
        // this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if (selection.length) {
        this.stopPolling()
      } else {
        this.startPolling()
      }
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加信息'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = '详情信息'
      this.currentItem = row
      this.showDetail = true
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateDyUserinfo(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addDyUserinfo(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除信息编号为"' + ids + '"的数据项？')
        .then(function() {
          return delDyUserinfo(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },

    handleOver(row) {
      const id = row.id || this.ids
      this.$modal
        .confirm('是否确认处理完成？')
        .then(function() {
          return updateDyUserinfo({ id, status: 200 })
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('处理成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.download(
        'system/dyUserinfo/export',
        {
          ...this.queryParams
        },
        `dyUserinfo_${new Date().getTime()}.xlsx`
      )
      this.ids = []
    }
  }
}
</script>
